//
// Created by DELL on 2024/7/22.
//
#include <iostream>
#include <coroutine>



struct Generator
{
    struct promise_type;
    using HandleType = std::coroutine_handle<promise_type>;

    explicit Generator(HandleType h) : handle(h) {}
    ~Generator()
    {
        handle.destroy();
    }

    struct promise_type
    {
        int num{0};

        Generator get_return_object()
        {
            return Generator(HandleType::from_promise(*this));
        }

        std::suspend_never initial_suspend()
        {
            return {};
        }

        std::suspend_always final_suspend() noexcept
        {
            return {};
        }

        void unhandled_exception()
        {
        }

        std::suspend_always yield_value(int n)
        {
            num = n;
            return {};
        }
        void return_void() {}

    };

    struct iterator
    {
        HandleType handle;

        int operator*() const
        {
            return handle.promise().num;
        }

        iterator operator++()
        {
            if (!handle.done())
            {
                handle();
//                handle.resume();
            }
            return *this;
        }

        bool operator!=(const iterator&) const
        {
            return !handle.done();
        }

    };

    iterator begin()
    {
        return {handle};
    }

    iterator end()
    {
        return {handle};
    }

    HandleType handle{};
};

Generator evenSequence(int n)
{
    for (int i = 1; i <= n; ++i)
    {
        co_yield i * 2;
    }
}


int main()
{
    for (auto n : evenSequence(5))
    {
        std::cout << n << ", ";
    }
    std::cout << std::endl;

    return 0;
}